<?php

class MediaCategoriesController extends Controller {
    const PAGE_SIZE= 16;
    
    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'list' and 'show' actions
                'actions' => array('show', 'index', 'ui'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    public function actionIndex() {
        $this->renderPartial('index', null, false, true);
    }

    public function actionUI() {
        $this->layout = 'contents';
        $this->render('ui');
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate() {
        $this->layout = 'contents';
        $model = new MediaCategory;
        if (isset($_POST['MediaCategory'])) {
            $model->attributes = $_POST['MediaCategory'];
            if ($model->save()) {
                Yii::app()->user->setFlash('createSuccess', Yii::t('mediaCategory', 'create_success'));
                $this->redirect(array('update', 'id' => $model->id));
            }
        }
        $this->render('create', array('model' => $model));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate() {
        $this->layout = 'contents';
        $model = $this->loadMediaCategory();
        if (isset($_POST['MediaCategory'])) {
            if ($_POST['MediaCategory']['id'] == $_POST['MediaCategory']['parent_id']) {
                $model->addError('parent_id', Yii::t('models/mediaCategory', 'parent_can_not_self'));
            } else {
                $model->attributes = $_POST['MediaCategory'];
                if ($model->save()) {
                    Yii::app()->user->setFlash('updateSuccess', Yii::t('mediaCategory', 'update_success'));
                    $this->redirect(array('update', 'id' => Yii::app()->request->getParam('id')));
                }
            }
        }
        $this->render('update', array('model' => $model));
    }

    /**
     * 根据选择删除分类信息，同时删除对应分类下的所有上传数据
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $delete_range = Yii::app()->request->getPost('delete_range');
            $id = Yii::app()->request->getParam('id');
            if ($delete_range < 0) $delete_range = 0;
            if ($delete_range == 0) {
                /**
                 * 只删除节点本身，此节点下的一级节点全部挂接到本节点的父节点
                 * A(1、0)
                 *   A1(2、1)
                 *   A2(3、1)
                 *     A2.1(4、3)
                 * 比如现在要删除的是节点 A2，删除之后的结构应该为
                 * A(1、0)
                 *   A1(2、1)
                 *   A2.1(4、1)
                 */
                $model = MediaCategory::model()->findByPk($id);
                $id_lists = MediaCategory::model()->getIds($id, false, true);
//                CVarDumper::dump($id_lists);
//                exit;
                if (count($id_lists)) {
//                    foreach ($id_lists as $list) {
                    $criteria = new CDbCriteria();
                    $criteria->addInCondition('id', $id_lists);
                    MediaCategory::model()->updateAll(array('parent_id' => $model->parent_id), $criteria);
//                        Node::model()->updateAll(array('parent_id' => $model->parent_id), 'id IN (:ids)', array('ids'=> $id_lists));
//                    }
                }
                $model->delete();
            } elseif ($delete_range == 1) {
                // 删除所有的分类数据，同时清空相应上传数据
                $id_lists = MediaCategory::model()->getIds($id);
                if (count($id_lists)) {
                    foreach ($id_lists as $id) {
                        MediaCategory::model()->findByPk($id)->delete();
                    }
                }
            }
            $this->redirect(array('ui'));
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }
    
    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadMediaCategory($id=null) {
        if($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=MediaCategory::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand() {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete') {
            $this->loadMediaCategory($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
